// ignore_for_file: must_be_immutable, avoid_print, use_build_context_synchronously

import 'package:dio/dio.dart';
import 'package:enjoy_plus/utils/eventbus.dart';
import 'package:enjoy_plus/utils/http.dart';
import 'package:enjoy_plus/utils/toast.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';

class ProfilePage extends StatefulWidget {
  ProfilePage({super.key, required this.userInfo});

  Map userInfo;

  @override
  State<ProfilePage> createState() => _ProfilePageState();
}

class _ProfilePageState extends State<ProfilePage> {
  Map userInfo = {
    "avatar": null,
    "nickName": null,
  };

  final TextEditingController _avatarController = TextEditingController();

  @override
  void initState() {
    super.initState();
    setState(() {
      userInfo = widget.userInfo;
      _avatarController.text = userInfo['nickName'] ?? '';
    });
  }

  updateNickName() async {
    if (_avatarController.text.isEmpty) {
      return ToastUtil.showError('昵称不能为空!');
    }
    if (_avatarController.text.length > 10) {
      return ToastUtil.showError('昵称长度不能超过10个字符!');
    }
    try {
      await http.put('/userInfo', data: {"nickName": _avatarController.text});
      setState(() {
        userInfo['nickName'] = _avatarController.text;
        ToastUtil.showSuccess('修改成功!');
      });
    } catch (e) {
      return ToastUtil.showError('网络异常!');
    }
  }

// 从相机或相册中选择图片
  showBottomSheet() {
    showModalBottomSheet(
        context: context,
        builder: (context) {
          return SizedBox(
              height: 200,
              child: Column(children: [
                ListTile(
                  leading: const Icon(Icons.camera_alt),
                  title: const Text('拍照'),
                  onTap: () async {
                    ImagePicker picker = ImagePicker();
                    final XFile? photo =
                        await picker.pickImage(source: ImageSource.camera);
                    if (photo != null) {
                      uploadAvatar(photo.path);
                    }
                  },
                ),
                ListTile(
                  leading: const Icon(Icons.photo),
                  title: const Text('相册'),
                  onTap: () async {
                    ImagePicker picker = ImagePicker();
                    final XFile? image =
                        await picker.pickImage(source: ImageSource.gallery);
                    if (image != null) {
                      uploadAvatar(image.path);
                    }
                  },
                )
              ]));
        });
  }

  uploadAvatar(String imagePath) async {
    try {
      // 1. 包装一个FormData对象
      FormData fd = FormData.fromMap({
        "file": kIsWeb
            ? MultipartFile.fromBytes(
                await XFile(imagePath).readAsBytes(),
                filename: 'avatar.jpg',
                contentType: DioMediaType('image', 'jpeg'),
              )
            : await MultipartFile.fromFile(imagePath),
        "type": "avatar"
      });
      // 2. 调用上传接口
      var res = await http.post('/upload', data: fd);
      if (res['code'] != 10000) return ToastUtil.showError('上传图片失败');
      // print(res);
      setState(() {
        userInfo['avatar'] = res['data']['url'];
        ToastUtil.showSuccess('上传图片成功');
      });
    } catch (e) {
      ToastUtil.showError('上传图片失败');
    } finally {
      Navigator.pop(context);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
        title: const Text('个人信息'),
        backgroundColor: Colors.transparent,
        centerTitle: true,
        actions: [
          IconButton(
            icon: const Icon(Icons.check),
            onPressed: () {
              updateNickName();
            },
          ),
          IconButton(
            icon: const Icon(Icons.add),
            onPressed: () {
              updateNickName();
            },
          )
        ],
        leading: IconButton(
          onPressed: () {
            eventBus.fire(RefreshMine());
            Navigator.pop(context);
          },
          icon: const Icon(Icons.arrow_back),
        ),
      ),
      body: ListView(
        padding: const EdgeInsets.all(10),
        children: [
          SizedBox(
            height: 40,
            child: Row(
              children: [
                const Text(
                  '头像',
                  style: TextStyle(fontSize: 16),
                ),
                const Spacer(),
                Row(
                  children: [
                    GestureDetector(
                        onTap: () {
                          showBottomSheet();
                        },
                        child: ClipRRect(
                            borderRadius: BorderRadius.circular(50.0),
                            child: userInfo['avatar'] != null
                                ? Image.network(userInfo['avatar'],
                                    width: 30, height: 30)
                                : Image.asset('images/avatar_1.jpg',
                                    width: 30, height: 30))),
                    const Icon(Icons.arrow_forward_ios, size: 12)
                  ],
                )
              ],
            ),
          ),
          Row(
            children: [
              const Text('昵称'),
              const Spacer(),
              Expanded(
                child: TextField(
                    controller: _avatarController,
                    decoration: const InputDecoration(
                      hintText: '请输入昵称',
                      border: InputBorder.none,
                    ),
                    textAlign: TextAlign.right,
                    onEditingComplete: () {
                      updateNickName();
                    }),
              ),
              const Icon(Icons.arrow_forward_ios, size: 12)
            ],
          )
        ],
      ),
    );
  }
}
